import { useCallback, useEffect, useRef, useState } from 'react'
import StepCardList from './StepCardList.tsx'
import {
  getCompanyInfoDetailProductStageCount,
  postCompanyInfoDetailProductCopyDrugLine,
  postCompanyInfoDetailProductMainProductService,
  postCompanyInfoDetailProductMedicalDevice,
  postCompanyInfoDetailProductNewDrugLine
} from '@/api/companyDetail/CompanyDevelopment.ts'
import {
  drugColumnTemp,
  drugtepDataTemp,
  genericsColumnTemp,
  genericsStepDataTemp,
  instrumentColumnTemp,
  instrumentStepDataTemp,
  serviceColumnTemp
} from './productionOpions'
import { Table } from 'antd'
import { initPageType, usePageChange } from '@hs-admin/utils'
import './ProductionInfo.css'
import { DetailModal } from '@hs-server/components'

const initPage: initPageType = {
  current: 1,
  total: 0,
  pageSize: 5,
  morePageOptions: {
    showSizeChanger: true,
    showQuickJumper: true,
    showTotal: (total: number) => `共 ${total} 条数据`,
    pageSizeOptions: [5]
  }
}

const ProductionInfo = ({ companyCode }: { companyCode: string }) => {
  // useState variables
  const [drugtepStepData, setDrugtepStepData] = useState(drugtepDataTemp)
  const [drugData, setDrugData] = useState([])
  const [drugDataTotal, setDrugDataTotal] = useState('')
  const [InstrumentTotal, setInstrumentTotal] = useState('')
  const [GenericDataTotal, setGenericDataTotal] = useState('')
  const [serviceDataTotal, setserviceDataTotal] = useState('')

  const DetailModalRef = useRef<any>(null)

  const getDrugData = useCallback(
    async (page: number, pageSize: number) => {
      const res = await postCompanyInfoDetailProductNewDrugLine({
        companyCode,
        pageNo: page,
        current: page,
        pageSize: pageSize
      })
      setDrugData(res.list ?? [])
      setDrugDataTotal(res.total ?? '')
      return res.total ?? 0
    },
    [companyCode]
  )
  const { pagination: drugPagination, resetPageAndTriggerRequest: drugResetPageAndTriggerRequest } = usePageChange(initPage, getDrugData)
  const drugCount = (drugPagination.current - 1) * drugPagination.pageSize

  useEffect(() => {
    drugResetPageAndTriggerRequest()
  }, [drugResetPageAndTriggerRequest])

  //仿制药一致性评价--
  const [genericsStepData, setGenericsStepData] = useState(genericsStepDataTemp)
  const [genericData, setGenericData] = useState([])

  const getGenericData = useCallback(
    async (page: number, pageSize: number) => {
      const res = await postCompanyInfoDetailProductCopyDrugLine({
        companyCode,
        pageNo: page,
        current: page,
        pageSize: pageSize
      })
      setGenericData(res.list ?? [])
      setGenericDataTotal(res.total ?? '')
      return res.total ?? 0
    },
    [companyCode]
  )
  const { pagination: genericPagination, resetPageAndTriggerRequest: genericResetPageAndTriggerRequest } = usePageChange(initPage, getGenericData)
  const genericCount = (genericPagination.current - 1) * genericPagination.pageSize
  useEffect(() => {
    genericResetPageAndTriggerRequest()
  }, [genericResetPageAndTriggerRequest])
  //医疗器械--
  const [instrumentStepData, setInstrumentStepData] = useState(instrumentStepDataTemp)
  const [instrumentData, setInstrumentData] = useState([])
  const getInstrumentData = useCallback(
    async (page: number, pageSize: number) => {
      const res = await postCompanyInfoDetailProductMedicalDevice({
        companyCode,
        pageNo: page,
        current: page,
        pageSize: pageSize
      })
      setInstrumentData(res.list ?? [])
      setInstrumentTotal(res.total ?? '')
      return res.total ?? 0
    },
    [companyCode]
  )
  const { pagination: instrumentPagination, resetPageAndTriggerRequest: instrumentResetPageAndTriggerRequest } = usePageChange(
    initPage,
    getInstrumentData
  )
  const instrumentCount = (instrumentPagination.current - 1) * instrumentPagination.pageSize
  useEffect(() => {
    instrumentResetPageAndTriggerRequest()
  }, [instrumentResetPageAndTriggerRequest])
  //企业主要产品服务--
  const [serviceData, setServiceData] = useState([])
  const getServiceData = useCallback(
    async (page: number, pageSize: number) => {
      const res = await postCompanyInfoDetailProductMainProductService({
        companyCode,
        pageNo: page,
        current: page,
        pageSize: pageSize
      })
      setServiceData(res.list ?? [])
      setserviceDataTotal(res.total ?? '')
      return res.total ?? 0
    },
    [companyCode]
  )
  const { pagination: servicePagination, resetPageAndTriggerRequest: serviceResetPageAndTriggerRequest } = usePageChange(initPage, getServiceData)
  const serviceCount = (servicePagination.current - 1) * servicePagination.pageSize
  useEffect(() => {
    serviceResetPageAndTriggerRequest()
  }, [serviceResetPageAndTriggerRequest])

  useEffect(() => {
    async function fetchData() {
      const result = await Promise.all([
        getCompanyInfoDetailProductStageCount({ productType: 0, companyCode }),
        getCompanyInfoDetailProductStageCount({ productType: 1, companyCode }),
        getCompanyInfoDetailProductStageCount({ productType: 2, companyCode })
      ])

      const arr = [setDrugtepStepData, setGenericsStepData, setInstrumentStepData]

      arr.forEach((item, index) => {
        const obj = result[index] ?? {}
        item((prevState) =>
          prevState.map((item) => {
            if (obj[item.label]) {
              return {
                ...item,
                value: obj[item.label]
              }
            }
            return item
          })
        )
      })
    }

    fetchData()
  }, [companyCode])

  const handleDetail = (row, flag) => {
    row.eventSubType = '产品研发'
    row.eventSegment = flag ? '新药管线' : '仿制药一致性评价'
    row.sourceId = row.meanTableId
    DetailModalRef.current.showModal(row)
  }

  const showProduction =
    drugtepStepData.some((item) => item.value) ||
    genericsStepData.some((item) => item.value) ||
    instrumentStepData.some((item) => item.value) ||
    serviceData.some((item) => item.value)

  const product = () => {
    const count = drugDataTotal + GenericDataTotal + InstrumentTotal + serviceDataTotal
    return count
  }

  return (
    <>
      {showProduction ? (
        <div id="产品信息" className="product-info" data-count={product()}>
          <div className="product-info-title">产品信息</div>
          {/* 新药管线 */}
          {drugtepStepData.some((item) => item.value) && (
            <div className="drug-content" id="新药管线" data-count={drugDataTotal}>
              <div className="product-info-sub-title">新药管线</div>
              <div className="product-info-card-list-content">
                <StepCardList data={drugtepStepData} dataLength={drugtepStepData.length} />
              </div>
              {drugData.length > 0 && (
                <div className="table-list">
                  <Table rowKey="id" columns={drugColumnTemp(handleDetail, drugCount)} dataSource={drugData} pagination={drugPagination} />
                </div>
              )}
            </div>
          )}

          {/* 仿制药一致性评价 */}
          {genericsStepData.some((item) => item.value) && (
            <div className="generics-content" id="仿制药管线" data-count={GenericDataTotal}>
              <div className="product-info-sub-title">仿制药管线</div>
              <div className="product-info-card-list-content">
                <StepCardList data={genericsStepData} dataLength={genericsStepData.length} />
              </div>
              {genericData.length > 0 && (
                <div className="table-list">
                  <Table
                    rowKey="id"
                    columns={genericsColumnTemp(handleDetail, genericCount)}
                    dataSource={genericData}
                    pagination={genericPagination}
                  />
                </div>
              )}
            </div>
          )}

          {/* 医疗器械 */}
          {instrumentStepData.some((item) => item.value) && (
            <div className="instrument-content" id="医疗器械" data-count={InstrumentTotal}>
              <div className="product-info-sub-title">医疗器械</div>
              <div className="product-info-card-list-content">
                <ul className="card-list-list">
                  {instrumentStepData.map((item, index) => (
                    <li key={index} className="card-list-list-item">
                      <div className={`item-box ${index === 0 ? 'is-active' : ''}`}>
                        <div className="title">{item.label}</div>
                        <div className="value">
                          {item.value}
                          <span className="unit">件</span>
                        </div>
                      </div>
                    </li>
                  ))}
                </ul>
              </div>
              {instrumentData.length > 0 && (
                <div className="table-list">
                  <Table
                    rowKey="id"
                    columns={instrumentColumnTemp(handleDetail, instrumentCount)}
                    dataSource={instrumentData}
                    pagination={instrumentPagination}
                  />
                </div>
              )}
            </div>
          )}
          {/* 企业主要产品服务 */}
          {serviceData.length > 0 && (
            <div className="service-content" id="主要产品服务" data-count={serviceDataTotal}>
              <div className="product-info-sub-title">主要产品服务</div>
              <div className="table-list">
                <Table rowKey="id" columns={serviceColumnTemp(serviceCount)} dataSource={serviceData} pagination={servicePagination} />
              </div>
            </div>
          )}
        </div>
      ) : null}
      <DetailModal ref={DetailModalRef} />
    </>
  )
}

export default ProductionInfo
